/* 荣威H5 详情页面 SKU
 * wangjingliang 2016-06-02
 */
 ;(function($, ECar) {
    "use strict";
//ios btn的active属性生效
    var a=document.getElementsByTagName('a');for(var i=0;i<a.length;i++){a[i].addEventListener('touchstart',function(){},false)}

// swiper初始化
    var swiper = new Swiper('#slides', {
        pagination : '#slides .swiper-pagination',
        onInit: function(swiper){
            var activeIndex=swiper.activeIndex+1;
            var imagesLoaded=swiper.imagesLoaded;
            $(".num_pagination .pagination-current").text(activeIndex);
            $(".num_pagination .pagination-total").text(imagesLoaded);
        },
        onSlideChangeEnd: function(swiper){
            var index=swiper.activeIndex+1;
            $(".num_pagination .pagination-current").text(index);
        }
    });



    var skuStatusMap = {"1039530":2,"1039531":0,"1039532":2,"1039550":2,"1039552":2,"1039551":2,"1039553":2,"1039538":2,"1039537":2,"1039539":2,"1039534":2,"1039533":2,"1039536":2,"1039535":2,"1039543":2,"1039542":2,"1039541":2,"1039540":2,"1039546":2,"1039547":2,"1039544":2,"1039545":2,"1039548":2,"1039549":2,"1039529":2,"1039528":2,"1039527":2};
    var arrDefault = ["CX11794","CX11798","CX11801"];
    var skuAttrCodeMap = {"CX11795@CX11799@CX11802":"1039533","CX11795@CX11799@CX11801":"1039534","CX11795@CX11797@CX11800":"1039529","CX11795@CX11797@CX11802":"1039527","CX11795@CX11799@CX11800":"1039535","CX11795@CX11797@CX11801":"1039528","CX11793@CX11799@CX11802":"1039551","CX11793@CX11799@CX11801":"1039552","CX11793@CX11799@CX11800":"1039553","CX11793@CX11797@CX11800":"1039547","CX11794@CX11797@CX11802":"1039536","CX11794@CX11797@CX11801":"1039537","CX11794@CX11797@CX11800":"1039538","CX11793@CX11798@CX11802":"1039548","CX11793@CX11798@CX11801":"1039549","CX11793@CX11798@CX11800":"1039550","CX11794@CX11798@CX11801":"1039540","CX11794@CX11798@CX11802":"1039539","CX11794@CX11798@CX11800":"1039541","CX11794@CX11799@CX11802":"1039542","CX11794@CX11799@CX11801":"1039543","CX11794@CX11799@CX11800":"1039544","CX11795@CX11798@CX11800":"1039532","CX11795@CX11798@CX11801":"1039531","CX11795@CX11798@CX11802":"1039530","CX11793@CX11797@CX11802":"1039545","CX11793@CX11797@CX11801":"1039546"};
    var attrMap = '';
    var currentSku = '1039527';

    var dimSku = [],
        goodType = $('.sku-box ul.flex_1'),
        dimNum = goodType.length,
        selectClass = 'select_active',
        item = $('.sku-box .select'),
        disabledClass = 'lose';

    //var arrDefault=['CX4','CX3','AY_2D0101_attr_14'];//默认选中的维度

    //创建数据集合
    goodType.each(function(i){
        var $this = $(this);
            $this.find('li[data-value='+arrDefault[i]+']').addClass(selectClass);
        var selected = $this.find('.'+selectClass),
            selectedValue = arrDefault[i],
            unselectObj = selected.siblings().not('.'+disabledClass);
            dimSku[i]={                
                className:selectClass,
                selectedObj:selected,
                unselectObj:unselectObj,
                vdLine:i,                
                selectedValue:selectedValue,
                _selectedValue:selectedValue
            };
    });

    function isCanClick(obj){  //是否可以点击
        return obj.hasClass(selectClass)||obj.hasClass(disabledClass);
    }

    function getCurrentDim(obj){
        return obj.data('dim');
    }

    function setStyle(obj){ //点击设置样式
        obj.addClass(selectClass).siblings().removeClass(selectClass);
    }

    function setValue(value,i,obj,unselectObj){ //获取维度值
        dimSku[i] = {                
            className:selectClass,
            selectedObj:obj,
            unselectObj:unselectObj,
            vdLine:i,           
            selectedValue:value,
            _selectedValue:value
        };
    }

    function getCurrentValue(obj){ //当前值
        return obj.data('value');
    }

    function getSkuString(name) {//通过sku查找skucode
        var str = [];
        if(dimNum > 1){
            for(var i in dimSku){           
                str.push(dimSku[i]['selectedValue']);          
            }
            return str.join('@');   
        }else{
            return dimSku[0]['selectedValue'];
        }             
    }

    //获取具体商品
    function getSkuCode(str){
        return skuAttrCodeMap[str];
    }

    function getSkuStatus(str){
        return skuStatusMap[str];
    }

    function arrToSting(strArr){
        return strArr.join('@');
    }

    function setStyleAfter(n, obj) {
        if(n != 2) {
            obj.addClass(disabledClass);
        } else {
            obj.removeClass(disabledClass);
        }
    }


    //当前未被选中的商品组合 遍列上下架情况
    function getUnProductColl(dim, dimSku) {   //dim 总维度    
        var arr = [];
        for(var i=0;i<dim;i++) {
            dimSku[i].unselectObj.each(function(j) {
                var $this = $(this),
                    arrPro = [];
                dimSku[i]._selectedValue = $this.data('value');              
                for(var k=0; k<dim; k++){                    
                    arrPro.push(dimSku[k].selectedValue);
                }                
                arrPro[i] = dimSku[i]._selectedValue;
                var skucode = getSkuCode(arrToSting(arrPro));
                
                var num = getSkuStatus(skucode);
                setStyleAfter(num, $this);
                arr.push(arrPro);
            });
        }
        return arr;
    }



    function itemClickAfter(obj,currentDim,url){     
        setStyle(obj);
        setValue(getCurrentValue(obj), currentDim,obj,obj.siblings().not('.'+disabledClass));
        var skutring = getSkuString('selectedValue'),
            skucode = getSkuCode(skutring);
        window.location.href = url+'?'+skucode;
    }

    //点击 SKU
    item.on('click',function(){  //setstyle      
        var $this=$(this);        
        if(isCanClick($this))return;
        var currentDim = getCurrentDim($this),
            url = $this.data('url');//当前维度
        itemClickAfter($this, currentDim,url);
        //getInventory(ajaxBack);
    });

    getUnProductColl(dimNum,dimSku);








    var setNumber = function(value,type,obj,btn,stock){
        var value = parseInt(value)<1?1:parseInt(value);
        switch (type) {
            case "reduce":
                if (value > 1) {
                    value = value - 1;
                }
                break;
            case "add":
                if (value < stock) {
                    value = value + 1;
                }
                break;
            case "input":
               value = value >= stock?stock:value;
        }
        obj.val(value);
        return value;
    }

    var setBtnStyle = function(type,value,stock) {
        if(stock <= value){
            $('.btn_'+type).addClass('disabled');
        }
        if(stock >value){
             $('.btn_number a').removeClass('disabled');
        }
        if(value==1 && type == "reduce"){
            $('.btn_'+type).addClass('disabled');
        }
    }

    var getSkuAjax = function(){
        return $.ajax({
            url:"/resources/js/skuAjax.js",
            async:false
        });
    }

    var handleSkuNum = function(count) {
        var nFlag = this.validSkuNum(count);
        if (nFlag === 0) {

            return count.replace("0", "");
        } else if (nFlag === -1) {
            return 1;
        } else {
            return count;
        }
    }

    // 校验商品数量是否符合规则
    var validSkuNum = function(count) {
        if(count=='')return 2;
        if (/^[1-9][0-9]?$/.test(count)) {
            return 1;
        } else if (/^0[1-9]$/.test(count)) {
            return 0;
        } else {
            return -1;
        }
    }


    var good_number = $('#good_number');

    $('div.btn_number a').on('click',function(e){
        var $this = $(this),
            inputObj = $('#good_number'),
            type = $this.data('btn-type'),
            value = inputObj.val();
        if($this.hasClass('disabled')) return;
        var stock = $.parseJSON(getSkuAjax().response);
        var newValue = setNumber(value,type,inputObj,$this,stock.skuStock);
        setBtnStyle(type,newValue,stock.skuStock);        
    });

    good_number.on('keyup',function(e){
        var sKeyCode = e.which || e.keyCode,
            sCount = $(this).val(),
            nFlag = validSkuNum(sCount);
        if ((sKeyCode >= 96 && sKeyCode <= 105) || (sKeyCode >= 48 && sKeyCode <= 57)) {
            return;
        }
        switch (nFlag) {
            case 0:
                sCount = 1;
                break;
            case -1:
                sCount = 1;
                break;
            default:
                return;
        }

        $(this).val(sCount);
    });

    good_number.on("change", function() {
        var sCount = $(this).val(),
            nFlag = validSkuNum(sCount);
        switch (nFlag) {
            case 0:
                sCount = 1;
                break;
            case -1,2:
                sCount = 1;
                break;
            default:
                var stock = $.parseJSON(getSkuAjax().response);
                var newValue = setNumber(sCount,'input',$(this),$(this),stock.skuStock);
                return;
        }        
        $(this).val(sCount);
    });








        




        




})(Zepto, window.ECar || (window.ECar = {}));